package com.ouman.pure.utils;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by jintian on 05/05/2017.
 */

public class HttpHelper {
    /*
    *  this class using for http post or get from server
    *
    */

    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;

    public String postJsonData(String requestURL, JSONObject jsonObject) throws IOException{
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        outputStream =  new DataOutputStream(httpConn.getOutputStream());

        // write jsonObject to output stream
        outputStream.write(jsonObject.toString().getBytes());
        outputStream.flush();
        outputStream.close();

        String response = "";
        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response += line;
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }

}
